package com.extensions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import javax.servlet.http.Part;


@ManagedBean(name = "fileUploadController")
//@RequestScoped
@SessionScoped
public class uploadFilesBean {

    //Primitives
    private static final int BUFFER_SIZE = 6124;
    private String folderToUpload;
    private Part file1;

    /**
     * Creates a new instance of UploadBean
     */
    public uploadFilesBean() {
    }
    
        public Part getFile1() {
        return file1;
    }

    public void setFile1(Part file1) {
        this.file1 = file1;
    }
    
     public void upload() throws IOException {

        file1.write("C:\\Users\\Leonhart10\\Documents\\uploads\\" + getFilename(file1));
        String file = "C:\\Users\\Leonhart10\\Documents\\uploads\\" + getFilename(file1);
        System.out.println(file);
        
        
        
    }
     
         private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
    

    public void handleFileUpload(FileUploadEvent event) {

//        ExternalContext extContext =
//                FacesContext.getCurrentInstance().getExternalContext();
//        File result = new File(extContext.getRealPath("//WEB-INF//" + event.getFile().getFileName()));
//        System.out.println(extContext.getRealPath("//WEB-INF//" + event.getFile().getFileName()));
//
//        try {
//            FileOutputStream fileOutputStream = new FileOutputStream(result);
//
//            byte[] buffer = new byte[BUFFER_SIZE];
//
//            int bulk;
//            InputStream inputStream = event.getFile().getInputstream();
//            while (true) {
//                bulk = inputStream.read(buffer);
//                if (bulk < 0) {
//                    break;
//                }
//                fileOutputStream.write(buffer, 0, bulk);
//                fileOutputStream.flush();
//            }
//
//            fileOutputStream.close();
//            inputStream.close();
//
//            FacesMessage msg =
//                    new FacesMessage("File Description", "file name: "
//                    + event.getFile().getFileName() + "<br/>file size: "
//                    + event.getFile().getSize() / 1024
//                    + " Kb<br/>content type: "
//                    + event.getFile().getContentType()
//                    + "<br/><br/>O arquivo foi enviado.");
//            FacesContext.getCurrentInstance().addMessage(null, msg);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//
//            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
//                    "Os arquivos não foram enviados!", "");
//            FacesContext.getCurrentInstance().addMessage(null, error);
//        }
        
        try {
            File targetFolder = new File("C:\\uploads\\");
            InputStream inputStream = event.getFile().getInputstream();
            OutputStream out = new FileOutputStream(new File(targetFolder,
                    event.getFile().getFileName()));
            String caminho = "C:\\uploads\\" + event.getFile().getFileName(); 
            System.out.println("Caminho: " + caminho); 
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            inputStream.close();
            out.flush();
            out.close();
            
            FacesMessage msg =
                    new FacesMessage("File Description", "file name: "
                    + event.getFile().getFileName() + "\nfile size: "
                    + event.getFile().getSize() / 1024
                    + " Kb\ncontent type: "
                    + event.getFile().getContentType()
                    + "\nO arquivo foi enviado com sucesso!");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (IOException e) {
            e.printStackTrace();
            
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Erro! O arquivo não foi enviado.", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
}